package com.code.god.mysql.util;

import com.code.god.mysql.constant.SQLConstant;
import com.code.god.mysql.init.InitObject;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.jdbc.metadata.HikariDataSourcePoolMetadata;

import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

import static com.code.god.mysql.init.InitObject.CONNECTIONS;
import static java.util.jar.Pack200.Packer.PASS;

public class MysqlUtil {

    static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
    static final String PATTERN = "jdbc:mysql://%s:%s";

    public static List<String> listDatabaes(Connection connection){
        Statement stmt = null;
        List<String> columns = new ArrayList<>();
        try {
            stmt = connection.createStatement();

            String sql = SQLConstant.SHOW_DATABASES;
            ResultSet rs=stmt.executeQuery(sql);
            while(rs.next()) {
                String db=rs.getString(1);
                columns.add(db);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return columns;
    }

    public static void createConnect(ConnectionObject connectionObject) throws Exception{
        String dbUrl = String.format(PATTERN,connectionObject.getHost(),connectionObject.getPort());

        HikariDataSource hikariDataSource = new HikariDataSource();
        hikariDataSource.setUsername(connectionObject.getUsername());
        hikariDataSource.setPassword(connectionObject.getPassword());
        hikariDataSource.setJdbcUrl(dbUrl);
        hikariDataSource.setDriverClassName(JDBC_DRIVER);

        hikariDataSource.evictConnection(hikariDataSource.getConnection());

        connectionObject.setDataSource(hikariDataSource);
        CONNECTIONS.put(connectionObject.getConnectionName(),connectionObject);
    }
}
